using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;

namespace Inikus.WinTimer
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            // only allow once instance of the application
            InstanceControl ic = new InstanceControl("WinTimer");
            if (ic.InstanceExists())
            {
                return;
            }

            // Add the event handler for handling UI thread exceptions to the event.
            Application.ThreadException += new ThreadExceptionEventHandler(Form_UIThreadException);

            // Set the unhandled exception mode to force all Windows Forms errors to go through
            // our handler.
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            // Add the event handler for handling non-UI thread exceptions to the event. 
            AppDomain.CurrentDomain.UnhandledException +=
                new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }

        #region exception handling

        // Handle the global UI exceptions 
        private static void Form_UIThreadException(object sender, ThreadExceptionEventArgs t)
        {
            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(
                    t.Exception, 
                    "General", 9, 100, System.Diagnostics.TraceEventType.Error);
            //bool rethrow = ExceptionPolicy.HandleException(t.Exception, "Exception Policy");
            MessageBox.Show("There was an unhandled exception in WinTimer.\r\n" +
                "Please send the 'trace.log' file to: wintimer@inikus.com\r\n\r\n"+
                t.Exception.Message, "WinTimer Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);

        }

        // Handle the global UI exceptions
        // NOTE: This exception cannot be kept from terminating the application - it can only 
        // log the event, and inform the user about it. 
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                if (e.ExceptionObject is Exception)
                {
                    Exception ex = (Exception)e.ExceptionObject;
                    Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(
                        ex, "General", 9, 100, System.Diagnostics.TraceEventType.Error);
                    //bool rethrow = ExceptionPolicy.HandleException(ex, "Exception Policy");

                    // Since we can't prevent the app from terminating, log this to the event log.
                    if (!EventLog.SourceExists("WinTimerException"))
                    {
                        EventLog.CreateEventSource("WinTimerException", "Application");
                    }

                    // Create an EventLog instance and assign its source.
                    EventLog myLog = new EventLog();
                    myLog.Source = "WinTimerException";
                    myLog.WriteEntry(ex.Message + "\n\nStack Trace:\n" + ex.StackTrace);

                    MessageBox.Show("There was an unhandled exception in WinTimer.\r\n" +
                        "Please send the 'trace.log' file to: wintimer@inikus.com\r\n\r\n" +
                        ex.Message, "WinTimer Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception exc)
            {
                try
                {
                    MessageBox.Show(exc.Message,
                           "Fatal Non-UI Error",
                            MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
                finally
                {
                    Application.Exit();
                }
            }
        }

        #endregion
    }
}